﻿/*
 * XtcpServer.h
 */
#ifndef __GDK_XTCPSERVER_H__
#define __GDK_XTCPSERVER_H__

#include <gdk/net/Socket.h>
#include <gdk/net/NetTcpServer.h>
#include <gdk/net/XtcpConnection.h>
#include <gdk/net/TcpEpoll.h>
#include <gdk/core/EventDispenser.h>
#include <gdk/core/MessageDispenser.h>
#include <gdk/core/Tick.h>
#include <map>
#include <list>

namespace gdk
{

	class GDK_NET_EXPORT XtcpServer : public Task
	{
		DECLARE_CLASS_HANDLE(XtcpServer)
		DECLARE_CLASS_INSTANCE(XtcpServer)

		class WaitSayHello
		{
		public:
			int32_t				_timeOut;
			NetTcpConnectionPtr	_tcpConn;
		};
		typedef std::map<Uuid,WaitSayHello> WaitSayHelloMap;
		typedef std::map<Uuid,NetTcpConnectionPtr> NetTcpConnectionMap;
		typedef std::list<XtcpConnectionPtr> NetXtcpConnectionList;

	private:
		TcpEpoll::Handle		_tcpEpoll;
		NetTcpServerPtr			_tcpServer;
		EventDispenser			_eventDispenser; //事件处理器
		WaitSayHelloMap			_tcpConnectionBacklog;
		NetTcpConnectionMap		_tcpConnectionAccept;
		NetXtcpConnectionList	_xtcpConnections;
		MessageDispenser<void>	_messageDispenser;
		Tick::Handle			_tickXtcpConnection;

	protected:
		XtcpServer(void);
		~XtcpServer(void);

	public:
		virtual bool start(System *system);
		virtual void stop(void);
		virtual void onTick(uint32_t timeSinceLastTick);
	protected:
		virtual void onAccept(void) {}
	private:
		void onTickXtcpConnection(uint32_t timeSinceLastTick);
		//-----------------------------------------------------------------------------

	public:
		virtual bool listen(unsigned short port, int nConnectionBacklog = 50);
		virtual bool accept(XtcpConnection *conn);
		virtual void close(void);
		//-----------------------------------------------------------------------------

	private:
		XtcpConnection* getXtcpConnection(const Uuid &targetId) const;
		//-----------------------------------------------------------------------------

	public:
		__INLINE__ EventDispenser& getEventDispenser(void) { return _eventDispenser; }
		//-----------------------------------------------------------------------------

	public:
		__INLINE__ bool isInvalid(void) const { return _tcpServer.isNull(); }
		__INLINE__ uint16_t getPort(void) const { return _tcpServer.isNull() ? 0 : _tcpServer->getPort(); }
		//-----------------------------------------------------------------------------

	private:
		void onTcpAccept(const Evt_NetTcpAccept *evt);
		void onTcpReceive(const Evt_NetTcpReceive *evt);
		//-----------------------------------------------------------------------------
	};
	typedef XtcpServer::Handle XtcpServerPtr;



} //namespace gdk


#endif //__GDK_XTCPSERVER_H__
